package com.android.monee.domain;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.android.monee.data.model.Mensuality;

public class RunningMensCalculator implements MensualityCalculator {

	private BudgetService budget;
	
	public RunningMensCalculator(BudgetService budget){
		this.budget = budget;
	}
	
	@Override
	public List<Mensuality> calcUndoneMensualities() {
		List<Mensuality> nextMensualities = new ArrayList<Mensuality>();
					
		if (budget.getRemainingAmount() > 0) {
			float amountToDistribute = budget.getRemainingAmount();
			int nbMensToDistribute = budget.getRemainingNbMens();
			int ceiledMensAmount = (int) Math.floor(amountToDistribute
					/ nbMensToDistribute);

			Set<Integer> nextMensNumbers = budget.getUndoneMensNumbers();

			for (Integer i : nextMensNumbers) {

				Mensuality mens = new Mensuality(budget);
				mens.setBudgetId(budget.getId());
				mens.setNumber(i);
				mens.setAmount(ceiledMensAmount);
				mens.setDate(budget.getDateForMensuality(mens.getNumber()));

				nextMensualities.add(mens);
			}

			float rest = amountToDistribute % nbMensToDistribute;
			for (Mensuality mens : nextMensualities) {
				if (rest > 0) {
					mens.setAmount(mens.getAmount() + 1);
					rest--;
				} else
					break;
			}
		}
				
		return nextMensualities;
	}
	
//	public List<Mensuality> calcNextMensualities1() {
//		List<Mensuality> nextMensualities = new ArrayList<Mensuality>();
//					
//		float amountToDistribute = budget.getRemainingAmount();
//		int nbMensToDistribute = budget.getRemainingNbMens();
//		int ceiledMensAmount = (int) Math.floor(amountToDistribute/nbMensToDistribute);
//		
//		Set<Integer> nextMensNumbers = budget.getUndoneMensNumbers();
//		
//		for(Integer i : nextMensNumbers){
//			
//			float mensAmount = 0;			
//			if(i == budget.getTotalNbMens())
//				mensAmount = amountToDistribute;
//			else
//				mensAmount = ceiledMensAmount;
//
//			amountToDistribute -= mensAmount;
//			
//			Mensuality mens = new Mensuality();
//			mens.setBudgetId(budget.getId());
//			mens.setNumber(i);
//			mens.setAmount(mensAmount);
//			mens.setDate(budget.getDateForMensuality(mens.getNumber()));
//			
//			nextMensualities.add(mens);
//		}
//		
//		return nextMensualities;
//	}
//	private Set<Integer> getUndoneMensNumbers(BudgetService budget){
//		SortedSet<Integer> allMensNumbers = new TreeSet<Integer>();
//		for(int i = 1 ; i <= budget.getTotalNbMens() ; i++){
//			allMensNumbers.add(i);
//		}
//		
//		List<MensualityService> doneMensualities = budget.getDoneMensualities();
//		List<MensualityService> cancelledMensualities = budget.getCancelledMensualities();
//		for(MensualityService mens : doneMensualities){
//			allMensNumbers.remove(mens.getNumber());
//		}
//		
//		for(MensualityService mens : cancelledMensualities){
//			allMensNumbers.remove(mens.getNumber());
//		}
//		
//		return allMensNumbers;
//	}

}
